package org.robot.utils;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;

import org.robot.pojo.Paper;
import org.robot.test.spider.spider2018.MyX509TrustManager;

/**
 * 系统在另一个域下拉数据
 * @author 99
 *
 */
public class HttpDownload {

	public static boolean saveContent(String urlString, String encoding, String path, Paper paper) {
		int i=0;
		boolean flag = download(urlString,encoding,path,paper);
		while(!flag&&i<3){
			 flag = download(urlString,encoding,path,paper);
			 ++i;
		}
		return flag;
		
	}
	
	public static boolean download(String urlString, String encoding, String path, Paper paper){
		try {
			File f = new File(path);
			if (!f.exists() && !f.isDirectory()) {
				f.mkdirs();
			}
			File file = new File(path + "\\" + paper.getPdfPathName());
			if (!file.exists()) {
				// String s = getContent(url, encoding);
				// 构造URL
				URL url = new URL(urlString);
				// 打开连接
				URLConnection con = url.openConnection();
				con.setReadTimeout(1000*60*10);
				con.setConnectTimeout(1000*10*2);
				if(con.getContentLength()==5){//代表返回是error
					return false;
				}
				// 输入流
				InputStream is = con.getInputStream();
				// 1K的数据缓冲
				byte[] bs = new byte[1024];
				// 读取到的数据长度
				int len;
				// 输出的文件流
				OutputStream os = new FileOutputStream(path + "\\" + paper.getPdfPathName());
				// 开始读取
				while ((len = is.read(bs)) != -1) {
					os.write(bs, 0, len);
				}
				// 完毕，关闭所有链接
				os.close();
				is.close();
				//判断下载下的文件大小是否等于服务器上文件大小
				int urlLength = paper.getPdfSize().intValue();
				File localfile = new File(path + "\\" + paper.getPdfPathName());
				long localLength = localfile.length();
				if(localLength == 0l){
					return false;
				}else if(urlLength != (int)localLength ){
					if(localfile.exists()){
						localfile.delete();
					}
					return false;
				}
			}
			// 读取pdf  如果读取成功则返回true，否则删除 返回false
			MatchEmail.getContent(file);
			return true;
		} catch (Exception e) {
			//读取或写入失败后，删除文件
			File f=new File(path+"/"+paper.getPdfPathName());
			if(f.exists()){
				f.delete();
			}
			return false;
		}
	}
	
	public static boolean saveContent(String urlString, String encoding, String path, String fileName) {
		int i=0;
		boolean flag = download(urlString,encoding,path,fileName);
		while(!flag&&i<3){
			 flag = download(urlString,encoding,path,fileName);
			 ++i;
		}
		return flag;
	}
	
	private static boolean download(String urlString, String encoding, String path, String fileName){
		try {
			File f = new File(path);
			if (!f.exists() && !f.isDirectory()) {
				f.mkdirs();
			}
			File file = new File(path + "\\" + fileName);
			if (!file.exists()) {
				// String s = getContent(url, encoding);
				// 构造URL
				URL url = new URL(urlString);
				// 打开连接
				URLConnection con = url.openConnection();
				con.setReadTimeout(1000*60*10);
				con.setConnectTimeout(1000*10*2);
				if(con.getContentLength()==5){//代表返回是error
					return false;
				}
				// 输入流
				InputStream is = con.getInputStream();
				// 1K的数据缓冲
				byte[] bs = new byte[1024];
				// 读取到的数据长度
				int len;
				// 输出的文件流
				OutputStream os = new FileOutputStream(path + "\\" + fileName);
				// 开始读取
				while ((len = is.read(bs)) != -1) {
					os.write(bs, 0, len);
				}
				// 完毕，关闭所有链接
				os.flush();
				os.close();
				is.close();
				return true;
			}
			return true;
		} catch (Exception e) {
			//读取或写入失败后，删除文件
			File f=new File(path+"/"+fileName);
			if(f.exists()){
				f.delete();
			}
			return false;
		}
	}
	public static void main(String[] args) {
		saveContent("http://www.jrse.cn/down/paperDown.aspx?id=2336604", "utf-8", "f:/", "aa.pdf");
	}
	
	/**
	 * 上传pdf
	 * @author hf
	 * @date 2014-9-9
	 */
	public static int uploadFile1(String fileName,String uploadUrl,Long taskId){
		try{
			int i=0;
			String result = uploadFile(fileName,uploadUrl);
			String str[]=fileName.split("/");
			String pdfName = str[str.length-1];
			String logPath = "d:/uploadpdflog/"+taskId+".log";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			while(null != result && result.equals("invaid ip")){
				System.out.println("--------------------invaid ip--------------------");
				appendWrite(sdf.format(new Date())+"   "+pdfName+"     上传失败,原因："+result+"", new File(logPath));
				Thread.sleep(10000);
				result = uploadFile(fileName,uploadUrl);
			}
			while((null != result && result.equals("false"))&& i<3){
				System.out.println(pdfName+"   上传失败,原因 ："+result+" "+StrUtils.getCurrentDateTime());
				appendWrite(sdf.format(new Date())+"   "+pdfName+"     上传失败,原因："+result+"", new File(logPath));
				result = uploadFile(fileName,uploadUrl);
				++i;
			}
			if(result!=null && result.contains("http")){
				System.out.println(pdfName+"   上传成功     "+StrUtils.getCurrentDateTime());
				appendWrite(sdf.format(new Date())+"   "+pdfName+"     上传成功", new File(logPath));
				return 1;
			}else{
				System.out.println(pdfName+"    上传失败 ,原因： "+result+"  "+StrUtils.getCurrentDateTime());
				appendWrite(sdf.format(new Date())+"   "+pdfName+"     上传失败 ,原因："+result+"", new File(logPath));
			}
			return 0;
		}catch (Exception e) {
			return 0; 
		}
	}
	
	/**
	 * 上传pdf
	 * @author hf
	 * @date 2014-9-4
	 * @param fileName 文件路径
	 * @param uploadUrl 上传路径
	 * 返回http链接地址为成功   invaid ip受限制  false失败
	 */
	private static String uploadFile(String fileName,String uploadUrl){
		try {
			 File file=new File(fileName);
			 String BOUNDARY = "---------7d4a6d158c9"; // 定义数据分隔
			 URL url = new URL(uploadUrl);   
			 HttpURLConnection conn = (HttpURLConnection) url.openConnection();   
		
			// 发POST请求必须设置如下两行   
             conn.setDoOutput(true);   
             conn.setDoInput(true);   
             conn.setUseCaches(false);   
             conn.setRequestMethod("POST");   
             conn.setRequestProperty("connection", "Keep-Alive");   
             conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");   
             conn.setRequestProperty("Charsert", "UTF-8");    
             conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);  
             
             OutputStream out = new DataOutputStream(conn.getOutputStream());  
             byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();//  
             StringBuilder sb = new StringBuilder();     
             sb.append("--");     
             sb.append(BOUNDARY);     
             sb.append("\r\n");     
             sb.append("Content-Disposition: form-data;name=\"file\";fileName=\""+ file.getName() + "\"\r\n");     
             sb.append("Content-Type:application/octet-stream\r\n\r\n");     
             byte[] data = sb.toString().getBytes();   
             out.write(data);
             DataInputStream in = new DataInputStream(new FileInputStream(file));
             int bytes = 0;   
             byte[] bufferOut = new byte[1024];   
             while ((bytes = in.read(bufferOut)) != -1) {   
                 out.write(bufferOut, 0, bytes);   
             }   
  
             in.close();  
             out.write(end_data);   
             out.flush();     
             out.close();    
  
             BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));   
             String line = null;
             StringBuffer returnSb=new StringBuffer("");
             while ((line = reader.readLine()) != null) {
            	 returnSb.append(line);
             }  
            return returnSb.toString();
		} catch (Exception e) {
//			e.printStackTrace();
			return e.toString();
		}
	}
	
	/**
	 * 追加文本
	 * @author hf
	 * @date 2014-9-9
	 */
	 public static boolean appendWrite(String str,File file){
		FileOutputStream fo = null;
		try {
			if(!file.getParentFile().exists())
				file.getParentFile().mkdirs();
			if (!file.exists())
				file.createNewFile();
			if (str == null)
				str = "";
			fo = new FileOutputStream(file.getPath(), true);
			str += "\r\n";
			fo.write(str.getBytes("utf-8"));
			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return false;
		} finally {
			if (fo != null){
				try {
					fo.close();
				} catch (IOException e1) {
					System.out.println(e1.getMessage());
				}	
			}
		}
	}
	 
	 
	 public static boolean getUrlPdfHttps(String website,File file){	
			InputStream in=null;
			FileOutputStream out=null;
			if(file.exists()){
				return true;
			}else{
				if(!file.getParentFile().exists()){
					file.getParentFile().mkdirs();
				}
			}
			try {
				SSLContext sslcontext = SSLContext.getInstance("SSL", "SunJSSE");//第一个参数为协议,第二个参数为提供者(可以缺省)
				TrustManager[] tm = {new MyX509TrustManager()};
				sslcontext.init(null, tm, new SecureRandom());
				HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
					public boolean verify(String s, SSLSession sslsession) {
						System.out.println("WARNING: Hostname is not matched for cert.");
							return true;
					}
				};
				HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
				HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
			
				URL url = new URL(website);
				HttpURLConnection conn = (HttpURLConnection)url.openConnection();
				conn.setRequestProperty("User-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2"); //处理403异常
				String str="";//截取网址域名
				if(website.startsWith("http://")){
					str="http://"+website.replace("http://", "").substring(0, website.replace("http://", "").indexOf("/"));
				}else if(website.startsWith("https://")){
					str="https://"+website.replace("https://", "").substring(0, website.replace("https://", "").indexOf("/"));
				}else{
					str=website.substring(0,website.indexOf("/"));
				}
				/**
				 * 不自动执行重定向操作
				 */
				conn.setInstanceFollowRedirects(true);//不自动执行重定向操作
				conn.setRequestMethod("GET");
				conn.setRequestProperty("Referer", str); 
				conn.setConnectTimeout(10000);
				conn.setReadTimeout(10000);
				if(conn.getResponseCode()==200){
					in = conn.getInputStream();
					out = new FileOutputStream(file);
					int len=-1;
					byte[] b = new byte[1024];
					while((len = in.read(b)) != -1){
						out.write(b,0,len);
					}
				}	
				
			} catch (Exception e) {
				e.printStackTrace();
			//log.error("TaskId:"+task.getPid()+" FilePath:"+file.getAbsolutePath()+"\n"+e.getMessage(), e);
				//读取或写入失败后，删除文件
				if(file.exists()){
					file.delete();
				}
				return false;
			}finally{
				try {
					if(in!=null)
					in.close();
					if(out!=null)
					out.close();
				} catch (Exception e2) {
//					e2.printStackTrace();
//					log.error("TaskId:"+task.getPid()+"\n"+e2.getMessage(), e2);
				}
				
			}
			if(file!=null && file.exists()){
				return true;
			}else{
				return false;
			}
		}

}
